package Arrays;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * @author 王艺锡
 * @version 1.0
 */
public class ArraysMethod {
    public static void main(String[] args) {
        int arr[] = {1,3,5,7,9};
        //1.遍历数组
        System.out.println(Arrays.toString(arr));


        //2.sort默认从小到大排序
        int arr1[] = {-1,25,18,-6,32};
        //因为数组是引用类型，所以通过排序后，会直接影响到实参
        Arrays.sort(arr1);
        System.out.println(Arrays.toString(arr1));


        //3.定制排序
        Integer arr2[] = {-1,25,18,-6,32};
        Arrays.sort(arr2, new Comparator() {//new Comparator()是一个匿名内部类，实现了接口Comparator
            @Override
            public int compare(Object o1, Object o2) {
                Integer i1 = (Integer) o1;
                Integer i2 = (Integer) o2;
                //return i1 - i2;//从小到大
                return i2 - i1;//从大到小
            }
        });
        System.out.println("====排序后====");
        System.out.println(Arrays.toString(arr2));


        //Exercise自己模拟
        int arr3[] = {-2,-6,32,18,26};
        bubble(arr3, new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                int i3 = (Integer) o1;
                int i4 = (Integer) o2;
                return i4 - i3;
            }
        });
        System.out.println("====定制排序后====");
        System.out.println(Arrays.toString(arr3));



        //4.binarySearch二分查找(折半查找)
        //返回索引，如果不存在则返回-(low + 1),low表示应该存在的位置
        Integer arr4[] = {18,26,32,58,99};
        int index = Arrays.binarySearch(arr4,89);
        System.out.println("index:" + index);


        //5.copyOf数组拷贝(被拷贝的数组，拷贝长度)
        //如果拷贝长度大于被拷贝数组的长度，则多余的部分赋null
        Integer newArr[] = Arrays.copyOf(arr4,arr4.length + 2);
        System.out.println(Arrays.toString(newArr));

        //6.fill数组填充
        Integer arr5[] = {1,2,3};
        Arrays.fill(arr5,99);
        System.out.println(Arrays.toString(arr5));


        //7.equals,比较两个数组是否相同
        Integer arr6[] = {99,99,99};
        boolean equals = Arrays.equals(arr5,arr6);
        System.out.println(equals);

        //8.asList,将一组值转换成List
        //1.asList方法，会将(1, 3, 5, 7, 9, 2)数据转换成一个List集合
        //2.返回的asList编译类型是List(接口)
        //3.asList运行类型是java.util.Arrays#ArraysList
        List asList = Arrays.asList(1, 3, 5, 7, 9, 2);
        System.out.println("asList:" + asList);
        System.out.println("asList的运行类型是" + asList.getClass());

    }

    public static void bubble(int arr[],Comparator c){
        int tmp = 0;
        for (int i = 0;i< arr.length-1;i++){
            boolean flag = false;
            for (int j = 0;j< arr.length - i - 1;j++){
                if(c.compare(arr[j],arr[j+1]) > 0){
                tmp = arr[j];
                arr[j] = arr[j+1];
                arr[j+1] = tmp;
                flag = true;
                }
            }
            if(flag == false){
                break;
            }
        }
    }
}
